namespace Brjnk.Common.UI
{
    using System;
    using System.Windows;
    using System.Windows.Media;
    using Brjnk.MVVM;

    /// <summary>
    /// </summary>
    public class VisualHost : FrameworkElement
    {
        private static readonly DependencyPropertyKey VisualsPropertyKey =
    DependencyProperty.RegisterReadOnly("Visuals", typeof(ObservableCollectionEx<Visual>), typeof(VisualHost), new PropertyMetadata());

        public static readonly DependencyProperty VisualsProperty = VisualsPropertyKey.DependencyProperty;

        public VisualHost()
        {
            SetValue(VisualsPropertyKey, new ObservableCollectionEx<Visual>());
            Visuals.ItemsAdded += new EventHandler<ItemsEventArgs<Visual>>(Visuals_ItemsAdded);
            Visuals.ItemsRemoved += new EventHandler<ItemsEventArgs<Visual>>(Visuals_ItemsRemoved);
        }

        public ObservableCollectionEx<Visual> Visuals
        {
            get { return (ObservableCollectionEx<Visual>)GetValue(VisualsProperty); }
        }

        //public void InvalidateVisual()
        //{
        //    this.InvalidateVisual();
        //}

        protected override int VisualChildrenCount
        {
            get
            {
                return Visuals.Count;
            }
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            if (Render != null) Render(this, new RenderEventArgs(drawingContext));
            base.OnRender(drawingContext);
        }

        protected override Visual GetVisualChild(int index)
        {
            return Visuals[index];
        }

        private void Visuals_ItemsAdded(object sender, ItemsEventArgs<Visual> e)
        {
            foreach (var v in e.Items)
                this.AddVisualChild(v);
        }

        private void Visuals_ItemsRemoved(object sender, ItemsEventArgs<Visual> e)
        {
            foreach (var v in e.Items)
                this.RemoveVisualChild(v);
        }

        public event EventHandler<RenderEventArgs> Render;
    }

    public class RenderEventArgs : EventArgs
    {
        public DrawingContext Context { get; protected set; }

        public RenderEventArgs(DrawingContext context)
        {
            this.Context = context;
        }
    }
}